/**
 * @author helio
 */
if(!SALE.dao) SALE.dao = {}
if(!SALE.dao.local) SALE.dao.local = {}
if(!SALE.dao.local.SaleBillDao) SALE.dao.local.SaleBillDao = function(){
	var billDoc;
}

SALE.dao.local.SaleBillDao.prototype = {
		/**
		 * 
		 */
		initBillDoc : function() {
			if(!this.billDoc) {
				this.billDoc = LocalXMLFileUtil.getBillDoc();
			}
			
			return this.billDoc;
		},
		
		saveBillDoc : function() {
			LocalXMLFileUtil.saveXML(this.billDoc,LocalXMLFileUtil.getBillFile());
		},
		
		insertBillInfo : function(billJson) {
			var root = this.billDoc.documentElement;
			var maxid = root.getAttribute("maxid");
			if(!maxid) {
				maxid = 0;
			}
			var id = parseInt(maxid) + 1;
			billJson["id"] = id;
			root.setAttribute("maxid",id);
			var billNode = this.billDoc.createElement("bill");
			
			this.updateBill(billJson, billNode);			
			root.appendChild(billNode);
			
			this.saveBillDoc();
			
			return id;
		},
		
		modifyBillInfo : function(billJson) {
			var billNode = this.searchBillByID(billJson.id);
			
			this.updateBill(billJson, billNode);
			
			this.saveBillDoc();
		},
		
		deleteBillInfo : function(id) {
			var billNode = this.searchBillByID(id);
			var root = this.billDoc.documentElement;
			if(billNode != null) {
				root.removeChild(billNode);
			}			
		},
		
		updateBill : function(billJosn, billNode) {
			for (var attri in billJosn) {
			
				if (attri.indexOf("old") != 0 && billJosn[attri] && billJosn[attri] != "") {
					var attriNodes = Ext.DomQuery.select("/" + attri, billNode);
					if (attriNodes != null && attriNodes.length > 0) {
						billNode.removeChild(attriNodes[0]);
					}
					
					var attriNode = this.billDoc.createElement(attri);
					billNode.appendChild(attriNode);
					
					if (attri == "details") {
						var details = billJosn.details;						
						for (var i = 0; i < details.length; i++) {
							var detail = details[i];
							var detailNode = this.billDoc.createElement("detail");
							attriNode.appendChild(detailNode);
							
							for (var attriDetail in detail) {
							
								var detailAttriNode = this.billDoc.createElement(attriDetail);
								contextNode = this.billDoc.createCDATASection(detail[attriDetail]);
								detailAttriNode.appendChild(contextNode);
								detailNode.appendChild(detailAttriNode);
							}
						}
					} else {						
						var contextNode = this.billDoc.createCDATASection(billJosn[attri]);
						attriNode.appendChild(contextNode);
					}
				}
				
			}	
		},
		
		searchBillByID : function(id) {
			var root = this.billDoc.documentElement;
			var objArray = Ext.query("bill:has(id:nodeValue(" + id+ "))", root);
			var result;
			
			if(objArray.length == 1) {
				result = objArray[0];
			}
			
			return result;
		},
		
		searchBillByCode : function(code) {
			var root = this.billDoc.documentElement;
			var objArray = Ext.query("bill:has(code:nodeValue(" + code+ "))", root);
			var result;
			
			if(objArray.length == 1) {
				result = objArray[0];
			}
			
			return result;
		},
		
		searchSaleBillJsonByCode : function(code) {
			var bill = this.searchBillByCode(code);
			
			if (bill) {
				var children = bill.childNodes;
				var billJson = {};
				
				for (var i = 0; i < children.length; i++) {
					var child = children[i];
					
					if (child.nodeType == 1) {
						if (child.nodeName == "details") {
							
							if (!billJson.details) {
								billJson.details = [];
							}
							
							var detailArray = Ext.query("/detail", child);
							
							Ext.each(detailArray, function(detail) {
								var attriArray = detail.childNodes;
								var detailJson = {}
								for (var j = 0; j < attriArray.length; j++) {
									var attri = attriArray[j];
									if (attri.nodeType == 1) {
										if (!detailJson[attri.nodeName] && attri.childNodes[0] != null) {
											detailJson[attri.nodeName] = attri.childNodes[0].nodeValue;
										}
									}
								}
								
								billJson.details.push(detailJson);								
							});
						} else {
							
							if (!billJson[child.nodeName] && child.childNodes[0] != null) {
								billJson[child.nodeName] = child.childNodes[0].nodeValue;
							}
						}
					}
				}	
				
				return billJson;
			}
		},
		
		searchSaleBillJson : function(id) {
			var bill = this.searchBillByID(id);
			
			if (bill) {
				var children = bill.childNodes;
				var billJson = {};
				
				for (var i = 0; i < children.length; i++) {
					var child = children[i];
					
					if (child.nodeType == 1) {
						if (child.nodeName == "details") {
							
							if (!billJson.details) {
								billJson.details = [];
							}
							
							var detailArray = Ext.query("/detail", child);
							
							Ext.each(detailArray, function(detail) {
								var attriArray = detail.childNodes;
								var detailJson = {}
								for (var j = 0; j < attriArray.length; j++) {
									var attri = attriArray[j];
									if (attri.nodeType == 1) {
										if (!detailJson[attri.nodeName] && attri.childNodes[0] != null) {
											detailJson[attri.nodeName] = attri.childNodes[0].nodeValue;
										}
									}
								}
								
								billJson.details.push(detailJson);								
							});
						} else {
							
							if (!billJson[child.nodeName] && child.childNodes[0] != null) {
								billJson[child.nodeName] = child.childNodes[0].nodeValue;
							}
						}
					}
				}	
				
				return billJson;
			}
		},
		
		/**
		 * 根据输入条件，查询销售单。
		 * @param {Object} condition
		 */
		searchSaleBillsArray : function(condition) {
			var root = this.billDoc.documentElement;
			var objArray;
			
			if(!condition.status || condition.status == "2") {
				objArray = Ext.query("bill:not(bill:has(end_flag:nodeValue(1)))", root);
			} else {
				if(condition.status == "1") {
					objArray = Ext.query("bill:has(status:nodeValue(true))", root);
				} else {
					objArray = Ext.query("bill:not(bill:has(status:nodeValue(true)))", root);
				}				
			}
			
			var result = [];
		    Ext.each(objArray, function(bill) {
				var filterFlag = false;
				for (var attri in condition) {
					if(attri != "status") {
						var tempAttri = attri.replace("_to", "");
						tempAttri = tempAttri.replace("_from", "");
						var node = Ext.DomQuery.select("/"+ tempAttri +"/*", bill)[0];
						
						if(condition[attri] != null && condition[attri] != "") {
							
							if(attri == "end_flag") {
								if(node && node.nodeValue == "1") {
									filterFlag = true;
								}								
								break;
							} 
							
							if(!node || node.nodeValue == null || node.nodeValue == "") {
								filterFlag = true;
								break;
							}
							
							
							
							if(attri.indexOf("date") > -1 && attri.indexOf("from") > -1) {
								if(Date.parse(node.nodeValue) < Date.parse(condition[attri].replaceAll("-", "/"))) {
									filterFlag = true;
									break;
								}
							} else if(attri.indexOf("_from") > -1) {
								if(node.nodeValue < condition[attri]) {
									filterFlag = true;
									break;
								}
							} else if(attri.indexOf("date") > -1 && attri.indexOf("_to") > -1) {
								if(Date.parse(node.nodeValue) > Date.parse(condition[attri].replaceAll("-", "/"))) {
									filterFlag = true;
									break;
								}
							} else if(attri.indexOf("_to") > -1) {
								if(node.nodeValue > condition[attri]) {
									filterFlag = true;
									break;
								}
							} else {
								if(node.nodeValue.toUpperCase().indexOf(condition[attri].toUpperCase()) < 0) {
									filterFlag = true;
									break;
								}
							}
						}
					}
				}
				
				if(!filterFlag) {
					var children = bill.childNodes;
					var nodeJson = {};
					for(var i = 0; i < children.length; i++) {
						var child = children[i];
						
						if(child.nodeType == 1) {
							if (!nodeJson[child.nodeName] && child.childNodes[0] != null) {
								nodeJson[child.nodeName] = child.childNodes[0].nodeValue;
							}
						}			
					}
					
					result.push(nodeJson);
				}

		    });
			return result;
		},
		
		searchSaleDailyStatus : function(daily, ignoreDate) {
			var dateArray = daily.toDateString().split(" ");
			
			var root = this.billDoc.documentElement;
			var objArray = Ext.query("bill:has(entry_date:contains("+ dateArray[3] +"))", root);
			var productsJson = {products: [],amount: 0};
			
			Ext.each(objArray, function(obj) {
				var entry_date = Ext.query("/entry_date/*", obj)[0];
				if (entry_date) {
					var date = entry_date.nodeValue;
									
					if (date.indexOf(dateArray[1]) > 0 && (ignoreDate || (date.indexOf(daily.toDateString()) == 0))) {
						
						var details = Ext.query("/details/detail:has(pcode)", obj);						
						Ext.each(details, function(detail){
							var code = Ext.query("/pcode/*", detail)[0].nodeValue;
							var number = Ext.query("/pnumber/*", detail)[0].nodeValue;
							var amount = Ext.query("/pamount/*", detail)[0].nodeValue;
							
							productsJson.amount = productsJson.amount + parseFloat(amount);
							
							var inArray = false;
							Ext.each(productsJson.products, function(product){
								if (product["code"] == code) {
								
									product["number"] = parseFloat(product["number"]) + parseFloat(number);
									product["amount"] = parseFloat(product["amount"]) + parseFloat(amount);
									product["price"] = parseFloat(product["amount"] / product["number"]).toFixed(2);
									inArray = true;
								}
							});
							
							if (!inArray) {
							
								var children = detail.childNodes;
								var productJson = {};
								for (var i = 0; i < children.length; i++) {
									var child = children[i];
									
									if (child.nodeType == 1) {
										if (!productJson[child.nodeName] && child.childNodes[0] != null) {
											productJson[child.nodeName.replace("p", "")] = child.childNodes[0].nodeValue;
										}
									}
								}
								
								productsJson.products.push(productJson);
							}
						});
					}
				}
		    });
			
			return productsJson;
		},
		
		searchSaleRecentlyDateStatus : function() {
			var result = [];
			var dateJson = SALE.Utils.createRecentlyDateJson();
			var dates = dateJson.dates;
			for(var i = dates.length - 1; i >= 0; i--) {
				var daily = dates[i].value;
				var dailyStatus = this.searchSaleDailyStatus(daily);
				
				result.push({
					date : dates[i].name,
					amount : dailyStatus.amount
				});	
			}
			
			return result;
		},
		
		searchProductRecentlyDateStatus : function(proCode) {
			var result = [];
			var dateJson = SALE.Utils.createRecentlyDateJson();
			var dates = dateJson.dates;
			for(var i = dates.length - 1; i >= 0; i--) {
				var daily = dates[i].value;
				var dailyStatus = this.searchSaleDailyStatus(daily);
				var findPro = false;
				for(var j = 0; j < dailyStatus.products.length; j++) {
					var product = dailyStatus.products[j];
					if(proCode == product.code) {
						result.push({
							date : dates[i].name,
							amount : product.amount
						});
						findPro = true;
						break;
					}
				}
				if(!findPro) {
					result.push({
						date : dates[i].name,
						amount : 0
					});
				}
			}
			
			return result;
		},
		
		searchSaleRecentlyMonthStatus : function() {
			var result = [];
			var dateJson = SALE.Utils.createRecentlyMonthJson();
			var dates = dateJson.monthes;
			for(var i = dates.length - 1; i >= 0; i--) {
				var daily = dates[i].value;
				var dailyStatus = this.searchSaleDailyStatus(daily,true);
				
				result.push({
					date : dates[i].name,
					amount : dailyStatus.amount
				});	
			}
			
			return result;
		},
		
		searchProductRecentlyMonthStatus : function(proCode) {
			var result = [];
			var dateJson = SALE.Utils.createRecentlyMonthJson();
			var dates = dateJson.monthes;
			for(var i = dates.length - 1; i >= 0; i--) {
				var daily = dates[i].value;
				var dailyStatus = this.searchSaleDailyStatus(daily,true);
				var findPro = false;
				for(var j = 0; j < dailyStatus.products.length; j++) {
					var product = dailyStatus.products[j];
					if(proCode == product.code) {
						result.push({
							date : dates[i].name,
							amount : product.amount
						});
						findPro = true;
						break;
					}
				}
				if(!findPro) {
					result.push({
						date : dates[i].name,
						amount : 0
					});
				}
			}
			
			return result;
		},
		
		/**
		 * 修改入库接收的数量。
		 * @param {Object} receiveJson
		 */	
		modifyBillProductShippingNumber : function(shippingJson) {
			var bill = this.searchSaleBillJsonByCode(shippingJson.bcode);
				
			if(bill) {
				var details = bill.details;
				var endFlag = true;
				for(var i = 0; i < details.length; i++) {
					var detail = details[i];
					
					if(shippingJson.index) {
						if(detail.index == shippingJson.index) {
							var pnumber = detail.pnumber != null && detail.pnumber != "" ? parseFloat(detail.pnumber) : 0;;
							var snumber = detail.snumber != null && detail.snumber != "" ? parseFloat(detail.snumber) : 0;
							var number = shippingJson.number;
							snumber = parseFloat(snumber) + parseFloat(number);
							detail.snumber = snumber;
						}
					} else if(detail.pcode == shippingJson.pcode) {
						var pnumber = detail.pnumber != null && detail.pnumber != "" ? parseFloat(detail.pnumber) : 0;;
						var snumber = detail.snumber != null && detail.snumber != "" ? parseFloat(detail.snumber) : 0;
						var number = shippingJson.number;
						snumber = parseFloat(snumber) + parseFloat(number);
						detail.snumber = snumber;
					}
					
					if(detail.snumber != detail.pnumber) {
						endFlag = false;
					}
				}
				
				if(endFlag) {
					bill.shipping_flag = 1;
				}
				
				this.modifyBillInfo(bill);
			}
		},
}